package com.elitetyc.eliteim.client.command;

import com.elitetyc.eliteim.client.command.anno.Command;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description 内部命令工厂
 * @Date 2021/9/17 14:53
 */
@Configuration
public class InnerCommandFactory implements InitializingBean {

    public final Map<String, InnerCommandInfo> innerCommandInfoHashMap = new HashMap<>();

    @Autowired
    private List<InnerCommand> innerCommandList;

    @Override
    public void afterPropertiesSet() throws Exception {
        for (InnerCommand innerCommand : innerCommandList) {
            final Command commandAno = innerCommand.getClass().getAnnotation(Command.class);
            if (innerCommandInfoHashMap.containsKey(commandAno.command())) {
                // 如果已存在这个命令，说明包含两个命令相同的内部命令，抛出异常
                throw new RuntimeException("包含两个相同的内部命令【】" + commandAno.command());
            } else {
                innerCommandInfoHashMap.put(commandAno.command(), new InnerCommandInfo(
                        commandAno.command(),
                        commandAno.desc(),
                        innerCommand.getClass().getName()
                ));
            }
        }
    }

    @Data
    @AllArgsConstructor
    public static class InnerCommandInfo {
        private String command;
        private String desc;
        private String clazz;
    }
}
